package com.zmn.plat.admin.controller.product;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.zmn.common.dto2.ResponseDTO;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Controller;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import com.zmn.common.utils.string.StringUtil;
import com.zmn.plat.common.constant.ProductConsts;
import com.zmn.plat.manager.dictionary.ProductDict;
import com.zmn.plat.common.exception.PlatException;
import com.zmn.plat.model.vo.product.ServProductBackVO;
import com.zmn.plat.model.vo.product.ServProductDescVO;
import com.zmn.plat.model.vo.product.ServProductVO;

/**
 * 描述: 产品管理修改控制
 *
 * @author tanbiao
 * @since: 2018/11/5 22:06
 */
@Controller
@RequestMapping("/tariffProduct/")
public class TariffServProductModifyController extends ServProductBaseController {

    private Logger logger = LoggerFactory.getLogger(TariffServProductModifyController.class);

    /**
     * region 新增/修改
     *
     * @param servProductVO
     *            产品新增修改实体
     * @return ModelAndView 执行结果
     * @author tanbiao
     * @since 15:38 2019/9/22
     */
    @RequestMapping(value = "addEdit")
    @ResponseBody
    @SuppressWarnings("Duplicates")
    @RequiresPermissions("/tariffProduct/addEditView.action")
    public ResponseDTO addEdit(HttpServletRequest request, @RequestBody ServProductVO servProductVO) {
        String lable = "新增产品";

        servProductVO.setShowType(ProductConsts.ET_PRODUCT_TYPE);
        try {
            String userName = getMcStaffRealName();
            if (servProductVO.getProductId() == null) {
                lable = "新增产品";
                String creater = getMcStaff().getRealName();
                servProductVO.setSort(servProductVO.getShowSort());
                Integer flag = servProductBService.insertAll(servProductVO, creater);
                if (flag.equals(ProductDict.FLAG_SUCCESS)) {
                    return ResponseDTO.success(true,"新增产品成功！");
                } else if (flag.equals(ProductDict.FLAG_TAFIFF_NAME_ERROR)) {
                    return ResponseDTO.fail("修改产品失败，计价器名称不能重复！");
                } else {
                    return ResponseDTO.fail("新增失败，产品名称不能重复！");
                }
            } else {
                lable = "修改产品";
                if (ProductDict.STATUS_ENABLE == servProductVO.getStatus()) {
                    List<Integer> idList = new ArrayList<>(1);
                    idList.add(servProductVO.getProductId());
                    List<ServProductBackVO> relationProducts = servProductService.listProductHasRelatedForTariff(idList);
                    if (!CollectionUtils.isEmpty(relationProducts)) {
                        return ResponseDTO.fail("计价器产品上架必须关联至少一个上架的后台产品；并且不能间接关联多个后台一级产品");
                    }
                }
                servProductVO.setSort(servProductVO.getShowSort());
                Integer flag = servProductBService.updateAll(servProductVO, userName);
                if (flag.equals(ProductDict.FLAG_SUCCESS)) {
                    return ResponseDTO.success(true,"修改产品成功！");
                } else if (flag.equals(ProductDict.FLAG_ATTR_ERROR)) {
                    return ResponseDTO.fail("修改产品失败，产品属性组合不能重复！");
                } else if (flag.equals(ProductDict.FLAG_TAFIFF_NAME_ERROR)) {
                    return ResponseDTO.fail("修改产品失败，计价器名称不能重复！");
                } else {
                    return ResponseDTO.fail("修改产品失败，产品名称不能重复！");
                }
            }
        } catch (Exception ex) {
            logger.error(lable + "失败", ex);
            return ResponseDTO.fail(lable + "失败！");
        }
    }

    /**
     * 添加产品描述
     *
     * @param request
     * @param servProductDescVO
     * @return
     * @author tanbiao
     * @since 15:38 2019/9/22
     */
    @RequestMapping(value = "addEditDesc")
    @ResponseBody
    @RequiresPermissions("/tariffProduct/editDescView.action")
    public ResponseDTO addEdit(HttpServletRequest request, @RequestBody ServProductDescVO servProductDescVO) {
        return super.addEdit(getMcStaffRealName(), servProductDescVO);
    }

    /**
     * 描述:修改产品状态
     *
     * @param ids
     *            产品ID组成的字符串 eg: productId1,productId2
     * @param status
     *            修改的状态
     * @return: ResponseDTO 执行结果
     * @auther: tanbiao
     * @since: 2018/11/5 22:39
     */
    @SuppressWarnings("Duplicates")
    @RequestMapping(value = "updateStatus")
    @ResponseBody
    @RequiresPermissions("/tariffProduct/updateStatus.action")
    public ResponseDTO updateStatus(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "ids", defaultValue = "") String ids, @RequestParam(value = "status", defaultValue = "0") int status) {

        if (StringUtil.isBlank(ids)) {
            return ResponseDTO.fail("请选择要更改状态的产品！");
        }

        List<Integer> productIds = StringUtil.convertStrsToList(ids);
        // 前台产品上架 需要判断是否关联后台产品，如果没有则提示“前台产品上架必须关联至少一个上架的后台产品”；20191023
        if (ProductDict.STATUS_ENABLE == status) {
            List<ServProductBackVO> relationProducts = servProductService.listProductHasRelatedForTariff(productIds);
            if (!CollectionUtils.isEmpty(relationProducts)) {
                StringBuilder stringBuilder = new StringBuilder();
                relationProducts.forEach(e -> stringBuilder.append(e.getProductId()).append(","));
                stringBuilder.deleteCharAt(stringBuilder.length() - 1);
                return ResponseDTO.fail("计价器产品[" + stringBuilder.toString() + "]上架必须关联至少一个上架的后台产品；并且不能间接关联多个后台一级产品！");
            }
        }

        try {
            servProductBService.updateStatusBatch(productIds, status, getMcStaffRealName(), ProductConsts.ET_PRODUCT_TYPE);
        } catch (PlatException e) {
            return ResponseDTO.fail(e.getMessage());
        }

        return ResponseDTO.success(true,"操作成功！");
    }

    /**
     * 描述:前端产品修改排序
     *
     * @param productId
     *            产品id
     * @param sort
     *            修改的状态
     * @return: ResponseDTO 执行结果
     * @auther: tanbiao
     * @since: 2018/11/5 22:39
     */
    @RequestMapping(value = "updateSort")
    @ResponseBody
    @RequiresPermissions("/tariffProduct/list.action")
    public ResponseDTO updateSort(HttpServletRequest request, HttpServletResponse response,
        @RequestParam(value = "id", defaultValue = "0") Integer productId, @RequestParam(value = "sort", defaultValue = "0") Integer sort) {

        if (productId == 0) {
            return ResponseDTO.fail("请选择要更改排序的产品！");
        }
        if (sort == 0) {
            return ResponseDTO.fail("请设置产品排序值！");
        }

        servProductService.updateShowSortByKey(productId, sort, getMcStaffRealName());
        return ResponseDTO.success(true,"操作成功！");
    }
}
